package com.mac.hosp_pre.order.util;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.order.config.AliyunConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SMSUtils {

    @Autowired
    private IAcsClient acsClient;

    @Autowired
    private AliyunConfig aliyunConfig;
     /**
      * 发送短信
      *
      * @param phoneNumbers 收信人手机号
      * @param param        发送的验证码参数
      */
     public void sendMessage(String phoneNumbers, Map<String, Object> param) {
         // 组装请求对象-具体描述见控制台-文档部分内容
         SendSmsRequest request = new SendSmsRequest();
         // 必填:待发送手机号
         request.setPhoneNumbers(phoneNumbers);
         // 必填:短信签名-可在短信控制台中找到
         request.setSignName(aliyunConfig.getSignName());
         // 必填:短信模板-可在短信控制台中找到
         request.setTemplateCode(aliyunConfig.getTemplateCode());
         // 选填：设置模板参数，多个参数用逗号隔开
         //param：随机生成的验证码
         request.setTemplateParam(JSON.toJSONString(param));
         try {
             // 获取发送结果
             SendSmsResponse response = acsClient.getAcsResponse(request);
             log.info("手机号:{},发送短信结果：{}",phoneNumbers,response.getMessage());
         } catch (ServerException e) {
             log.error("sms服务端错误:{}",e);
             throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
         } catch (ClientException e) {
             log.error("sms客户端错误:{}",e);
             throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
         }
     }
 }

 